<template>
  <el-dialog
    title="分配角色"
    :visible="showAssignDialog"
    width="600px"
    @close="close"
    @open="open"
  >
    <el-checkbox-group v-model="newRoleIds" v-loading="loading">
      <el-checkbox v-for="v in roleIds" :key="v.id" :label="v.id">
        {{ v.name }}
      </el-checkbox>
    </el-checkbox-group>
    <div slot="footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="handelConfirm">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { reqGetRoleList } from '@/api/setting'
import { reqGetUserDetailById } from '@/api/user'
import { reqEditAssignRoles } from '@/api/employees'

export default {
  name: 'AssignRole',
  props: {
    // 显示弹出层的数据
    showAssignDialog: { type: Boolean, default: false },
    userId: { type: String, default: null },
  },
  data() {
    return {
      roleIds: [],
      newRoleIds: [],
      loading: false,
    }
  },
  async created() {
    // 一、获取角色列表
    const data = await reqGetRoleList()
    // console.log(data)
    this.roleIds = data.rows
  },
  methods: {
    // 二、关闭弹框触发的事件
    close() {
      this.$emit('closeAssignDialog')
    },

    // 三、弹出层打开时的回调
    async open() {
      this.loading = true
      const data = await reqGetUserDetailById(this.userId)
      // console.log(data)
      this.newRoleIds = data.roleIds
      this.loading = false
    },

    // 四、点击确认触发的事件
    async handelConfirm() {
      // 1.发送请求,重新分配用户角色
      if (this.newRoleIds.length === 0) return this.$message.error('请至少选择一个角色')
      await reqEditAssignRoles(this.userId, this.newRoleIds)
      this.$message.success('分配角色成功')
      // 2.关闭弹出层
      this.close()
    },
  },
}
</script>

<style lang="scss" scoped>
.el-checkbox {
  display: inline-block;
}
</style>
